import Vue from 'vue';
import Loading from './LoadingUtils.vue';

const LoadingConstructor = Vue.extend(Loading);

const loadingInstance = new LoadingConstructor({
  el: document.createElement('div'),
});

document.body.appendChild(loadingInstance.$el);

let timeoutId = null;

const showLoading = (message = 'Loading...', timeout = 10000) => {
  loadingInstance.show(message);

  if (timeoutId) {
    clearTimeout(timeoutId);
  }

  timeoutId = setTimeout(() => {
    loadingInstance.hide();
  }, timeout);
};

const hideLoading = () => {
  if (timeoutId) {
    clearTimeout(timeoutId);
  }
  loadingInstance.hide();
};

export default {
  install(Vue) {
    Vue.prototype.$loadingU = {
      show: showLoading,
      hide: hideLoading,
    };
  },
};
